<template>
  <div class="managers-page">
    <div class="page-header">
      <h1>客户经理管理</h1>
      <p class="subtitle">管理客户经理账号，包括添加、编辑和删除操作</p>
    </div>

    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索客户经理..."
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="action-section">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          添加客户经理
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="managers"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="fullName" label="姓名" width="120">
          <template #default="{ row }">
            {{ row.fullName }}
          </template>
        </el-table-column>
        <el-table-column label="客户数量" width="100">
          <template #default="{ row }">
            {{ row._count?.clientAssignments || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="工作日志" width="100">
          <template #default="{ row }">
            {{ row._count?.workLogs || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="info"
              @click="showClientsDialog(row)"
              :disabled="row._count?.clientAssignments === 0"
            >
              查看客户 ({{ row._count?.clientAssignments || 0 }})
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑客户经理' : '添加客户经理'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="form.fullName" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            :placeholder="isEdit ? '留空则不修改密码' : '请输入密码'"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 客户列表对话框 -->
    <el-dialog
      v-model="clientsDialogVisible"
      :title="`${currentManager?.fullName} 的客户列表`"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="clients-dialog-content">
        <!-- 搜索栏 -->
        <div class="search-section" style="margin-bottom: 16px;">
          <el-input
            v-model="clientSearchQuery"
            placeholder="搜索客户..."
            style="width: 300px"
            clearable
            @input="handleClientSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 客户表格 -->
        <el-table
          v-loading="clientsLoading"
          :data="clients"
          stripe
          style="width: 100%"
          max-height="400"
        >
          <el-table-column prop="clientCode" label="客户编码" width="120" />
          <el-table-column prop="clientName" label="客户名称" width="200" />
          <el-table-column prop="marketType" label="市场类型" width="100" />
          <el-table-column prop="terminalType" label="终端类型" width="120" />
          <el-table-column label="服务项目" width="200">
            <template #default="{ row }">
              <el-tag
                v-for="assignment in row.serviceAssignments"
                :key="assignment.service.id"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ assignment.service.serviceName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="工作日志" width="100">
            <template #default="{ row }">
              {{ row._count?.workLogs || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper" style="margin-top: 16px;">
          <el-pagination
            v-model:current-page="clientCurrentPage"
            v-model:page-size="clientPageSize"
            :page-sizes="[10, 20, 50]"
            :total="clientTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleClientSizeChange"
            @current-change="handleClientCurrentChange"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Message, MessageBox } from '@/utils/message';
import { Search, Plus, Refresh } from '@element-plus/icons-vue';
import { trpc } from '../../utils/trpc';

// 响应式数据
const loading = ref(false);
const submitting = ref(false);
const managers = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

// 客户列表对话框相关
const clientsDialogVisible = ref(false);
const clientsLoading = ref(false);
const clients = ref([]);
const clientTotal = ref(0);
const clientCurrentPage = ref(1);
const clientPageSize = ref(10);
const clientSearchQuery = ref('');
const currentManager = ref(null);

// 表单数据
const form = reactive({
  id: 0,
  username: '',
  fullName: '',
  password: '',
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '姓名长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { 
      validator: (rule: any, value: string, callback: Function) => {
        if (!isEdit.value && !value) {
          callback(new Error('请输入密码'));
        } else if (value && (value.length < 6 || value.length > 100)) {
          callback(new Error('密码长度在 6 到 100 个字符'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-';

  try {
    const date = new Date(dateString);
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('无效的日期字符串:', dateString);
      return '-';
    }

    // 使用中文格式显示日期
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (error) {
    console.error('日期格式化错误:', error, '原始值:', dateString);
    return '-';
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const response = await trpc.manager.list.query({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value || undefined,
    });
    
    if (response.success) {
      managers.value = response.data.data;
      total.value = response.data.pagination.total;
    } else {
      Message.error(response.message || '加载数据失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    Message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadData();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadData();
};


// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (row: any) => {
  isEdit.value = true;
  form.id = row.id;
  form.username = row.username;
  form.fullName = row.fullName;
  form.password = '';
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.id = 0;
  form.username = '';
  form.fullName = '';
  form.password = '';
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    let response;
    if (isEdit.value) {
      const updateData: any = {
        id: form.id,
        username: form.username,
        fullName: form.fullName,
      };
      if (form.password) {
        updateData.password = form.password;
      }
      response = await trpc.manager.update.mutate(updateData);
    } else {
      response = await trpc.manager.create.mutate({
        username: form.username,
        fullName: form.fullName,
        password: form.password,
      });
    }
    
    if (response.success) {
      Message.success(response.message || (isEdit.value ? '更新成功' : '创建成功'));
      dialogVisible.value = false;
      loadData();
    } else {
      Message.error(response.message || (isEdit.value ? '更新失败' : '创建失败'));
    }
  } catch (error) {
    console.error('提交失败:', error);
    Message.error('操作失败');
  } finally {
    submitting.value = false;
  }
};

// 删除处理
const handleDelete = async (row: any) => {
  try {
    await MessageBox.confirm(
      `确定要永久删除客户经理 "${row.fullName}" 吗？此操作将级联删除相关的分配关系和工作日志，且不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await trpc.manager.delete.mutate({ id: row.id });
    
    if (response.success) {
      Message.success(response.message || '删除成功');
      loadData();
    } else {
      Message.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      Message.error('删除失败');
    }
  }
};

// 显示客户列表对话框
const showClientsDialog = (manager: any) => {
  currentManager.value = manager;
  clientsDialogVisible.value = true;
  clientCurrentPage.value = 1;
  clientSearchQuery.value = '';
  loadClientData();
};

// 加载客户数据
const loadClientData = async () => {
  if (!currentManager.value) return;

  clientsLoading.value = true;
  try {
    const response = await trpc.manager.clients.query({
      managerId: currentManager.value.id,
      page: clientCurrentPage.value,
      pageSize: clientPageSize.value,
      search: clientSearchQuery.value || undefined,
    });

    if (response.success) {
      clients.value = response.data.data;
      clientTotal.value = response.data.pagination.total;
    } else {
      Message.error(response.message || '加载客户数据失败');
    }
  } catch (error) {
    console.error('加载客户数据失败:', error);
    Message.error('加载客户数据失败');
  } finally {
    clientsLoading.value = false;
  }
};

// 客户搜索处理
const handleClientSearch = () => {
  clientCurrentPage.value = 1;
  loadClientData();
};

// 客户分页处理
const handleClientSizeChange = (size: number) => {
  clientPageSize.value = size;
  clientCurrentPage.value = 1;
  loadClientData();
};

const handleClientCurrentChange = (page: number) => {
  clientCurrentPage.value = page;
  loadClientData();
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.managers-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.subtitle {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.search-section {
  flex: 1;
  min-width: 300px;
}

.action-section {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 已删除记录样式 */
.deleted-record {
  color: #999;
  text-decoration: line-through;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-section {
    min-width: auto;
  }
  
  .action-section {
    justify-content: center;
  }
}
</style>
